package com.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usercenter.common.ErrorCode;
import com.usercenter.contant.UserConstant;
import com.usercenter.exception.BusinessException;
import com.usercenter.model.User;
import com.usercenter.service.UserService;
import com.usercenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
* @author Vv
* @description 用户服务实现类
* @createDate 2024-06-22 20:00:58
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    
    @Resource
    private UserMapper userMapper;
    
    private static final String SALT = "Vv";
    
    
   
    
    @Override
    public long UserRegister(String userAccount, String userPassword, String checkPassword,String planetCode) {
        // 1. 校验
        if(StringUtils.isAllEmpty(userAccount,userPassword,checkPassword,planetCode)){
            throw  new BusinessException(ErrorCode.NULL_ERROR,"参数为空");
        }
        //  账号长度 不小于 6位
        if(userAccount.length() < 6){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR,"账户长度小于6位");
        }
        //  密码 不小于 8位
        if(userPassword.length() < 8 || checkPassword.length() < 8){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR," 密码小于8位");
        }
        if(planetCode.length() > 5){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR," planet Code 超过 五位");
        }
        //账户不能包含特殊字符
        String validPattern="[\\u00A0\\s\"`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(matcher.find()){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR," 账户包含特殊字符");
        }
        //密码和校验密码相同
        if(!userPassword.equals(checkPassword)){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR,"密码和校验密码不相同");
        }
        //   账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if(count > 0){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR,"账户重复");
        }
        
        //   编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode",planetCode);
        count = userMapper.selectCount(queryWrapper);
        if(count > 0){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR,"编号重复");
        }
        //2. 加盐
        
        String encryptPassword= DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        
        //3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        int result = userMapper.insert(user);
        if(result != 1){
            throw  new BusinessException(ErrorCode.NULL_ERROR,"插入失败请重试");
        }
        return user.getId();
    }
    
    @Override
    public User UserLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if(StringUtils.isAllEmpty(userAccount,userPassword)){
            throw  new BusinessException(ErrorCode.NULL_ERROR,"账户 或者密码为空");
        }
        //  账号长度 不小于 6位
        if(userAccount.length() < 6){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR,"账户长度小于6位");
        }
        //  密码 不小于 8位
        if(userPassword.length() < 8){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR," 密码小于8位");
        }
        //账户不能包含特殊字符
        String validPattern="[\\u00A0\\s\"`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(matcher.find()){
            throw  new BusinessException(ErrorCode.PANARENT_ERROR," planet Code 超过 五位");
        }
        
        //2. 加盐
        String encryptPassword= DigestUtils.md5DigestAsHex(("SALT"+userPassword).getBytes());
        
        //   查询账户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if(user == null){
            log.info("user login failed ,UserAccount cannot match UserPassword");
            throw  new BusinessException(ErrorCode.PANARENT_ERROR,"账户不存在");
        }
        //3.用户脱敏
        User cleanUser = getSafeUser(user);
        //4.记录用户登录状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,cleanUser);
        return cleanUser;
    }
    
    @Override
    public User getSafeUser(User user) {
        User cleanUser = new User();
        cleanUser.setId(user.getId());
        cleanUser.setUsername(user.getUsername());
        cleanUser.setUserAccount(user.getUserAccount());
        cleanUser.setAvatarUrl(user.getAvatarUrl());
        cleanUser.setGender(user.getGender());
        cleanUser.setPhone(user.getPhone());
        cleanUser.setEmail(user.getEmail());
        cleanUser.setUserStatus(user.getUserStatus());
        cleanUser.setCreateTime(user.getCreateTime());
        cleanUser.setUserRole(user.getUserRole());
        cleanUser.setPlanetCode(user.getPlanetCode());
        return cleanUser;
    }
    
    @Override
    public int UserLogout(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }
}




